package com.hyjy.music.service

import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.*
import com.hyjy.music.service.IService.MusicListener
import com.hyjy.music.util.showToast

/**
 * 音乐播放服务
 */
class MusicService : Service(), Runnable {
    private var url = ""
    private var mediaPlayer: MediaPlayer = MediaPlayer()
    private var musicHandler = Handler(Looper.getMainLooper())
    private var musicListener: MusicListener? = null

    override fun run() {
        val currentPosition = mediaPlayer.currentPosition
        val duration = mediaPlayer.duration
        musicListener?.onMusicProgressChange(url, currentPosition, duration)
        musicHandler.postDelayed(this, 16L) // 16ms更新一次播放进度
    }

    override fun onCreate() {
        super.onCreate()
        mediaPlayer.setOnErrorListener { _: MediaPlayer, what: Int, _: Int ->
            showToast("MusicService onError,$what")
            false
        }
        mediaPlayer.setOnCompletionListener {
            this@MusicService.musicListener?.onMusicCompletion()
        }
    }

    override fun onBind(intent: Intent): IBinder {
        return MusicBinder()
    }

    override fun onDestroy() {
        super.onDestroy()
        stop()
    }

    private inner class MusicBinder : Binder(), IService {
        override fun startMusic(url: String, reset: Boolean) = start(url, reset)

        override fun pauseMusic() = pause()

        override fun stopMusic() = stop()

        override fun isMusicPlaying() = mediaPlayer.isPlaying

        override fun seekMusicTo(sec: Int) = mediaPlayer.seekTo(sec)

        override fun setMusicListener(listener: MusicListener) {
            this@MusicService.musicListener = listener
        }
    }

    private fun start(url: String, reset: Boolean) {
        kotlin.runCatching {
            this.url = url
            if (reset) {
                mediaPlayer.reset()
                mediaPlayer.setDataSource(url)
                mediaPlayer.prepare()
            }
            if (!mediaPlayer.isPlaying) {
                mediaPlayer.start()
            }
            musicHandler.removeCallbacksAndMessages(null)
            musicHandler.post(this@MusicService)
        }.onFailure {
            showToast("MusicService start error:$it")
        }
    }

    private fun pause() {
        if (mediaPlayer.isPlaying) {
            mediaPlayer.pause()
        }
        musicHandler.removeCallbacksAndMessages(null)
    }

    private fun stop() {
        mediaPlayer.stop()
        mediaPlayer.release()
        musicHandler.removeCallbacksAndMessages(null)
    }
}